﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;
using Microsoft.Reporting.WinForms;

namespace TMS
{
    public partial class CreateEditInternalDispatchNoteControl : UserControl
    {
        Categories cat = new Categories();
        DataSet table = new DataSet();
        Product prod = new Product();
        Int32 ProductCounter = 0;
         
        Users ActiveUser = Program.GetActiveUser;
        bool edit = false;
        bool init = false;
        bool print = false;
        DateTime Today = DateTime.Today;
        public string FromWarehouse;
        public string ToWarehouse;
        string Responsible;
        int NoteNumber;


        public CreateEditInternalDispatchNoteControl()
        {
            InitializeComponent();


            dgvProductsList.ColumnCount = 8;
            dgvProductsList.Columns[0].HeaderText = "Бр.";
            dgvProductsList.Columns[1].HeaderText = "Бр.на Пр.";
            dgvProductsList.Columns[2].HeaderText = "Име";
            dgvProductsList.Columns[3].HeaderText = "Опис";
            dgvProductsList.Columns[4].HeaderText = "Ед.М.";
            dgvProductsList.Columns[5].HeaderText = "Количина";
            dgvProductsList.Columns[6].Visible = false;
            dgvProductsList.Columns[7].HeaderText = "Магацин";
            dgvProductsList.Columns[0].Width = 30;
            dgvProductsList.Columns[1].Width = 80;
            dgvProductsList.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

        }

        public CreateEditInternalDispatchNoteControl(DataGridViewRow row)
        {
            Program.GetMainForm.Text = "TMS - Интерна испратница бр." + row.Cells[0].Value.ToString();
            edit = true;
            InitializeComponent();

            dgvProductsList.ColumnCount = 9;
            dgvProductsList.Columns[0].HeaderText = "Бр.";
            dgvProductsList.Columns[1].HeaderText = "Бр.на Пр.";
            dgvProductsList.Columns[2].HeaderText = "Име";
            dgvProductsList.Columns[3].HeaderText = "Опис";
            dgvProductsList.Columns[4].HeaderText = "Ед.М.";
            dgvProductsList.Columns[5].HeaderText = "Количина";
            dgvProductsList.Columns[6].Visible = false;
            dgvProductsList.Columns[7].Visible = false;
            dgvProductsList.Columns[8].Visible = false;
            dgvProductsList.Columns[0].Width = 30;
            dgvProductsList.Columns[1].Width = 80;
            dgvProductsList.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            FromWarehouse = row.Cells[5].Value.ToString();
            ToWarehouse = row.Cells[6].Value.ToString();
            NoteNumber = Convert.ToInt32(row.Cells[0].Value.ToString());
            FillInternalDispatcNoteProductsList(Convert.ToInt32(row.Cells[0].Value.ToString()));

            if (row.Cells[4].Value.ToString() == "Затворена")
            {
                btnSave.Visible = false;
                btnAdd.Visible = false;
                btnEditRemove.Visible = false;
                grbAddProduct.Visible = false;
            }
           
        }

        private void CreateEditReceiveNoteControl_Load(object sender, EventArgs e)
        {
            cmbCategory1.DisplayMember = "name";
            cmbCategory1.ValueMember = "id";
            cmbCategory2.DisplayMember = "name";
            cmbCategory2.ValueMember = "id";
            cmbCategory3.DisplayMember = "name";
            cmbCategory3.ValueMember = "id";
        }

        private bool Add()
        {
            object[] product = new object[9];
            ProductCounter = dgvProductsList.Rows.Count + 1;

            Int64 quantity = Convert.ToInt64(txtQuantity.Text);
            DataSet table = new DataSet();

            foreach (DataGridViewRow row in dgvProductsList.Rows)
                if ((row.Cells[2].Value.ToString() == cmbProductList.Text.ToString()))
                {
                    MessageBox.Show("Производот веќе се наоѓа во листата\nМожете да ја промените количината");
                    row.Selected = true;
                    dgvProductsList.FirstDisplayedScrollingRowIndex = row.Index;
                    return false;
                }

            table = prod.GetProductFromDBAsDataSet(Convert.ToInt32(cmbProductList.SelectedValue));
            product[0] = ProductCounter;
            product[1] = table.Tables[0].Rows[0].ItemArray[5];
            product[2] = table.Tables[0].Rows[0].ItemArray[4].ToString();
            product[3] = table.Tables[0].Rows[0].ItemArray[10];
            product[4] = table.Tables[0].Rows[0].ItemArray[11];
            product[5] = quantity;
            product[6] = table.Tables[0].Rows[0].ItemArray[0];
            product[7] = FromWarehouse;
            product[8] = ToWarehouse;

            Color RowColor = new Color();
            if (quantity > prod.GetProductQuantityFromWarehouse(Convert.ToInt32(table.Tables[0].Rows[0].ItemArray[0]), FromWarehouse))
                RowColor = Color.Red;
            else
                RowColor = Color.Black;


            if (dgvProductsList.SelectedRows.Count == 0)
            {
                dgvProductsList.Rows.Add(product);
                dgvProductsList.Rows[dgvProductsList.RowCount - 1].DefaultCellStyle.ForeColor = RowColor;
            }
            else
            {
                dgvProductsList.Rows.Insert(dgvProductsList.SelectedRows[0].Index, product);
                dgvProductsList.Rows[dgvProductsList.SelectedRows[0].Index].DefaultCellStyle.ForeColor = RowColor;
            }

            Int32 i = 1;
            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {
                row.Cells[0].Value = i;
                i++;
            }
            return true;
        }

        private void cmbCategory1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cmbCategory1.Items.Count == 0) cmbCategory1.DataSource = cat.GetAllCategory1().Tables[0];
            else
            {
                if (cmbCategory1.SelectedValue.ToString() == "1")
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else 
                {
                    cmbCategory2.DataSource = cat.GetAllCategory2(cmbCategory1.SelectedValue.ToString()).Tables[0];
                    cmbCategory3.DataSource = cat.GetAllCategory3(cmbCategory1.SelectedValue.ToString(), "").Tables[0];
                }
            }
            cmbProductList.DisplayMember = "Name";
            cmbProductList.ValueMember = "ID";
        }

        private void cmbCategory2_SelectedValueChanged(object sender, EventArgs e)
        {

            if (cmbCategory2.Items.Count == 0) cmbCategory2.DataSource = cat.GetAllCategory2("").Tables[0];
            else
            {
                if (cmbCategory2.SelectedValue.ToString() == "1")
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
                }
                else
                {
                    cmbCategory3.DataSource = cat.GetAllCategory3("", cmbCategory2.SelectedValue.ToString()).Tables[0];
                }
            }

        }

        private void cmbCategory3_SelectedValueChanged(object sender, EventArgs e)
        {
            
            if (cmbCategory3.Items.Count == 0) cmbCategory3.DataSource = cat.GetAllCategory3("", "").Tables[0];
            if (cmbCategory2.SelectedValue.ToString()!="System.Data.DataRowView")
                if (cmbCategory3.SelectedValue.ToString() != "System.Data.DataRowView")
                {

                    table = prod.GetProductFromDB(cmbCategory1.SelectedValue.ToString(), cmbCategory2.SelectedValue.ToString(), cmbCategory3.SelectedValue.ToString());
                    cmbProductList.Text = "";
                    cmbProductList.DataSource = table.Tables[0];
                    cmbProductList.Update();
                }
        }

        private void btnEditRemove_Click(object sender, EventArgs e)
        {

            if (dgvProductsList.SelectedRows.Count != 0)
            {
                cmbProductList.SelectedValue = dgvProductsList.SelectedRows[0].Cells[6].Value;
                txtQuantity.Text = dgvProductsList.SelectedRows[0].Cells[5].Value.ToString();
                foreach (DataGridViewRow row in dgvProductsList.SelectedRows)
                {
                    dgvProductsList.Rows.Remove(row);
                }
                Int32 i = 1;
                foreach (DataGridViewRow row in dgvProductsList.Rows)
                {
                    row.Cells[0].Value = i;
                    i++;
                }
            }
        }

        public void FillInternalDispatcNoteProductsList(Int32 ID)
        {
            DataSet table = new DataSet();
            MySqlDataAdapter MyDA = new MySqlDataAdapter();
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;


            MySqlConnection mysqlCon = new MySqlConnection(connString);
            mysqlCon.Open();


            string sqlSelectAll = "SELECT internal_dispatch_products.*,warehouse.Quantity from internal_dispatch_products LEFT JOIN warehouse ON warehouse.Warehouse=internal_dispatch_products.FromWarehouse AND warehouse.Product_ID=internal_dispatch_products.ProductID WHERE Note_ID='" + ID + "'";
            MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, mysqlCon);
            MyDA.Fill(table);
           

            foreach (DataRow row in table.Tables[0].Rows)
            {
                DataSet prod1 = prod.GetProductFromDBAsDataSet(Convert.ToInt32(row.ItemArray[1]));
                object[] product = new object[9];
                product[0] = row.ItemArray[4];
                product[1] = prod1.Tables[0].Rows[0].ItemArray[5];
                product[2] = prod1.Tables[0].Rows[0].ItemArray[4];
                product[3] = prod1.Tables[0].Rows[0].ItemArray[10];
                product[4] = prod1.Tables[0].Rows[0].ItemArray[11];
                product[5] = row.ItemArray[2];
                product[6] = row.ItemArray[1];
                product[7]=row.ItemArray[5];
                product[8] = row.ItemArray[6];

                Color RowColor = new Color();

                if (Convert.ToInt32(row.ItemArray[2]) > Convert.ToInt32(row.ItemArray[7]))
                    RowColor = Color.Red;
                else
                    RowColor = Color.Black;
                
                dgvProductsList.Rows.Add(product);
                dgvProductsList.Rows[dgvProductsList.RowCount - 1].DefaultCellStyle.ForeColor = RowColor;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            prod.DeleteAllProductsFromInternalDispatchNoteList(NoteNumber);
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

            MySqlConnection mysqlCon = new MySqlConnection(connString);

            mysqlCon.Open();

            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {

                string sqlInsertProduct = "INSERT INTO internal_dispatch_products VALUES (DEFAULT,'" +
                                            Convert.ToInt32(row.Cells[6].Value) + "','" +
                                            Convert.ToInt32(row.Cells[5].Value) + "','" +
                                            NoteNumber + "','" +
                                            Convert.ToInt32(row.Cells[0].Value) + "','" +
                                            row.Cells[7].Value.ToString() + "','" +
                                            row.Cells[8].Value.ToString()+"')";
                MySqlCommand cmd = new MySqlCommand(sqlInsertProduct, mysqlCon);
                cmd.ExecuteNonQuery();

            }
            mysqlCon.Close();
            this.Dispose();
            Program.GetMainForm.ShowControl(ControlsEnum.INTERNAL_DISPATCHES_CONTROL);
        }

       

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //if (print)
            //{
            //    btnPrint.Text = "Печати";
            //    dgvProductsList.Visible = true;
            //    grbAddProduct.Visible = true;
            //    btnAdd.Visible = true;
            //    btnEditRemove.Visible = true;
            //    print = false;
            //    rpvStocktakingReport.Visible = false;
            //}
            //else
            //{
            //    btnPrint.Text = "Излези";
            //    dgvProductsList.Visible = false;
            //    grbAddProduct.Visible = false;
            //    btnAdd.Visible =false;
            //    btnEditRemove.Visible = false;
            //    print = true;
            //    rpvStocktakingReport.Visible = true;

            //    StocktakingListData ds = new StocktakingListData();
            //    foreach (DataGridViewRow row in dgvProductsList.Rows)
            //    {
            //        ds.Tables[0].Rows.Add(new object[] { row.Cells[0].Value.ToString(), row.Cells[1].Value.ToString(), row.Cells[2].Value.ToString(), row.Cells[3].Value.ToString(), row.Cells[5].Value.ToString(), row.Cells[7].Value.ToString() });
            //    }

            //    ReportParameter StocktakingDate = new ReportParameter("StocktakingDate", NewStocktaking.Date.ToString("dd-MM-yyyy"));
            //    ReportParameter ActiveUserPar = new ReportParameter("ActiveUser", Responsible);
            //    ReportParameter date = new ReportParameter("Date", Today.ToString("dd-MM-yyyy"));
            //    ReportParameter description = new ReportParameter("StocktakingListDescription", lbStocktakingListDescription.Text);

            //    ReportDataSource rds = new ReportDataSource("DS1", ds.Tables[0]);
            //    this.rpvStocktakingReport.LocalReport.DataSources.Add(rds);
            //    this.rpvStocktakingReport.LocalReport.SetParameters(StocktakingDate);
            //    this.rpvStocktakingReport.LocalReport.SetParameters(ActiveUserPar);
            //    this.rpvStocktakingReport.LocalReport.SetParameters(date);
            //    this.rpvStocktakingReport.LocalReport.SetParameters(description);
            //    this.rpvStocktakingReport.RefreshReport();
                
            //}
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Add();
        }

        private void ToStBack_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Back())
                this.Dispose();
        }


        private void ToStForward_Click(object sender, EventArgs e)
        {
            if (Program.GetMainForm.Forward())
                this.Dispose();
        }

        private void ToStSave_Click(object sender, EventArgs e)
        {
            prod.DeleteAllProductsFromInternalDispatchNoteList(NoteNumber);
            string connString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

            MySqlConnection mysqlCon = new MySqlConnection(connString);

            mysqlCon.Open();

            foreach (DataGridViewRow row in dgvProductsList.Rows)
            {

                string sqlInsertProduct = "INSERT INTO internal_dispatch_products VALUES (DEFAULT,'" +
                                            Convert.ToInt32(row.Cells[6].Value) + "','" +
                                            Convert.ToInt32(row.Cells[5].Value) + "','" +
                                            NoteNumber + "','" +
                                            Convert.ToInt32(row.Cells[0].Value) + "','" +
                                            row.Cells[7].Value.ToString() + "','" +
                                            row.Cells[8].Value.ToString() + "')";
                MySqlCommand cmd = new MySqlCommand(sqlInsertProduct, mysqlCon);
                cmd.ExecuteNonQuery();

            }
            mysqlCon.Close();
            this.Dispose();
            
            Program.GetMainForm.ShowControl(ControlsEnum.INTERNAL_DISPATCHES_CONTROL);
        }
    }
}
